package com.aipartner.service.impl;

import com.aipartner.dto.AiImageRequest;
import com.aipartner.dto.AiImageResponse;
import com.aipartner.entity.AiImageExample;
import com.aipartner.entity.AiImageHistory;
import com.aipartner.entity.AiImageExampleChat;
import com.aipartner.entity.UserWorkLike;
import com.aipartner.mapper.AiImageExampleMapper;
import com.aipartner.mapper.AiImageHistoryMapper;
import com.aipartner.mapper.AiImageExampleChatMapper;
import com.aipartner.mapper.UserWorkLikeMapper;
import com.aipartner.service.AiImageService;
import com.fasterxml.jackson.databind.JsonNode;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.springframework.web.multipart.MultipartFile;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.util.StringUtils;

/**
 * AI图片生成服务实现类
 * 
 * @author AI Partner Team
 * @since 2024-01-20
 */
@Slf4j
@Service
public class AiImageServiceImpl implements AiImageService {
    
    @Autowired
    private DoubaoPaintingClient doubaoPaintingClient;
    
    @Autowired
    private AiImageHistoryMapper historyMapper;
    
    @Autowired
    private AiImageExampleMapper exampleMapper;
    
    @Autowired
    private AiImageExampleChatMapper exampleChatMapper;
    
    @Autowired
    private UserWorkLikeMapper userWorkLikeMapper;
    
    @Autowired
    private com.aipartner.mapper.UserWorkMapper userWorkMapper;

    @Autowired
    private com.aipartner.service.CreditsService creditsService;
    
    @Value("${file.upload.generated-images-path:./uploads/generated-images/}")
    private String uploadPath;
    
    @Value("${file.upload.generated-images-url-prefix:/uploads/generated-images/}")
    private String urlPrefix;
    
    @Value("${app.external-base-url:http://localhost:8080}")
    private String externalBaseUrl;
    
    @Value("${file.upload.reference-images-path:./uploads/reference-images/}")
    private String referenceImagesPath;
    
    @Value("${file.upload.reference-images-url-prefix:/uploads/reference-images/}")
    private String referenceImagesUrlPrefix;
    
    @Override
    public AiImageResponse generateImage(AiImageRequest request) {
        log.info("Starting image generation for user: {}, prompt: {}", request.getUserId(), request.getPrompt());
        log.info("🔍 AiImageRequest参数检查: referenceImagePath={}", request.getReferenceImagePath());
        
        // 检查积分是否足够并消耗积分
        Long requiredCredits = creditsService.getServiceCreditsCost("ai_image");
        if (requiredCredits == null) {
            requiredCredits = 10L; // 默认10积分
        }
        
        if (!creditsService.checkCreditsEnough(request.getUserId(), requiredCredits)) {
            throw new RuntimeException("积分不足，需要" + requiredCredits + "积分才能生成图片");
        }
        
        try {
            // 调用豆包绘画API生成图片
            log.info("调用豆包绘画API生成图片: prompt={}, size={}, style={}, referenceImage={}", 
                request.getPrompt(), request.getSize(), request.getStyle(), 
                request.getReferenceImagePath() != null ? "已提供" : "无");
            log.info("🎯 传递给DoubaoPaintingClient的referenceImagePath: {}", request.getReferenceImagePath());
            JsonNode apiResponse = doubaoPaintingClient.submitImageTask(
                request.getPrompt(), 
                request.getSize(), 
                request.getStyle(),
                request.getReferenceImagePath()
            );
            log.info("豆包绘画API响应: {}", apiResponse.toString());
            
            // 生成唯一任务ID
            String taskId = UUID.randomUUID().toString();
            
            // 保存到数据库
            AiImageHistory history = new AiImageHistory();
            history.setUserId(request.getUserId());
            history.setPrompt(request.getPrompt());
            history.setSize(request.getSize());
            history.setStyle(request.getStyle());
            history.setReferenceImageUrl(request.getReferenceImagePath()); // 保存参考图URL
            history.setTaskId(taskId);
            
            // 解析豆包绘画API响应（支持多张图片）
            List<String> imageUrls = new ArrayList<>();
            List<String> imageBase64s = new ArrayList<>();

            log.info("开始解析豆包API响应，原始响应: {}", apiResponse.toString());

            if (apiResponse.has("data")) {
                JsonNode dataNode = apiResponse.get("data");
                log.info("API响应data节点: isArray={}, size={}", dataNode.isArray(), dataNode.isArray() ? dataNode.size() : 0);
                
                // 豆包绘画API返回格式: {"data": [{"url": "...", "b64_json": "..."}]}
                if (dataNode.isArray() && dataNode.size() > 0) {
                    for (int i = 0; i < dataNode.size(); i++) {
                        JsonNode item = dataNode.get(i);
                        log.info("处理第{}张图片: {}", i + 1, item.toString());
                        
                        // 优先获取URL
                        if (item.has("url")) {
                            String url = item.get("url").asText();
                            imageUrls.add(url);
                            log.info("添加图片URL: {}", url);
                        }
                        // 如果没有URL，尝试获取base64
                        else if (item.has("b64_json")) {
                            String base64 = item.get("b64_json").asText();
                            imageBase64s.add(base64);
                            log.info("添加图片base64，长度: {}", base64.length());
                        }
                    }
                }
            }
            
            log.info("解析完成 - URL数量: {}, Base64数量: {}", imageUrls.size(), imageBase64s.size());

            // 处理多张图片并保存到本地
            List<String> finalUrls = new ArrayList<>();
            
            // 处理URL格式的图片
            for (int i = 0; i < imageUrls.size(); i++) {
                String imageUrl = imageUrls.get(i);
                if (imageUrl != null && !imageUrl.isEmpty()) {
                    String subTaskId = taskId + "_" + (i + 1); // 为每张图片生成独立ID
                    String finalUrl = downloadImageFromUrl(imageUrl, subTaskId);
                    finalUrls.add(finalUrl);
                }
            }
            
            // 处理base64格式的图片
            for (int i = 0; i < imageBase64s.size(); i++) {
                String imageBase64 = imageBase64s.get(i);
                if (imageBase64 != null && !imageBase64.isEmpty()) {
                    String subTaskId = taskId + "_" + (finalUrls.size() + i + 1);
                    String finalUrl = saveBase64Image(imageBase64, subTaskId);
                    finalUrls.add(finalUrl);
                }
            }
            
            // 临时解决方案：如果只有一张图片，复制三份
            if (finalUrls.size() == 1) {
                String originalUrl = finalUrls.get(0);
                try {
                    // 复制第一张图片生成第二、三张
                    for (int i = 2; i <= 3; i++) {
                        String newTaskId = taskId + "_" + i;
                        String copiedUrl = copyImage(originalUrl, newTaskId);
                        finalUrls.add(copiedUrl);
                    }
                    log.info("已将单张图片复制为3张: {}", finalUrls);
                } catch (Exception e) {
                    log.warn("复制图片失败: {}", e.getMessage());
                }
            }

            if (finalUrls.isEmpty()) {
                String errorMsg = apiResponse.has("message") ? apiResponse.get("message").asText() : "未找到图片数据";
                history.setStatus(AiImageHistory.STATUS_FAILED);
                historyMapper.insert(history);
                return AiImageResponse.failed(taskId, request.getPrompt(), errorMsg);
            }

            // 将第一张图片URL保存到历史记录，完整URL列表放在响应中
            history.setImageUrl(finalUrls.get(0));
            history.setStatus(AiImageHistory.STATUS_SUCCESS);
            historyMapper.insert(history);
            
            // 生成成功，消耗积分
            boolean creditsConsumed = creditsService.consumeCredits(
                request.getUserId(), 
                requiredCredits, 
                "ai_image", 
                taskId, 
                "AI生图：" + request.getPrompt()
            );
            
            if (creditsConsumed) {
                log.info("积分消耗成功 - 用户: {}, 消耗积分: {}, 任务: {}", request.getUserId(), requiredCredits, taskId);
            } else {
                log.warn("积分消耗失败 - 用户: {}, 任务: {}", request.getUserId(), taskId);
            }
            
            // 创建包含多张图片的响应
            AiImageResponse response = AiImageResponse.success(finalUrls.get(0), taskId, request.getPrompt(), request.getSize(), request.getStyle());
            // 添加所有图片URL到响应中
            response.setImageUrls(finalUrls);
            return response;
            
        } catch (Exception e) {
            log.error("图片生成过程中发生异常: {}", e.getMessage(), e);
            e.printStackTrace(); // 打印完整堆栈跟踪
            return AiImageResponse.failed(null, request.getPrompt(), "图片生成失败: " + e.getMessage());
        }
    }
    
    @Override
    public AiImageResponse queryTaskStatus(String taskId) {
        log.info("Querying task status: {}", taskId);
        
        try {
            // 先从数据库查询
            LambdaQueryWrapper<AiImageHistory> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(AiImageHistory::getTaskId, taskId);
            AiImageHistory history = historyMapper.selectOne(wrapper);
            
            if (history == null) {
                return AiImageResponse.failed(taskId, "", "任务不存在");
            }
            
            // 如果已经完成，直接返回结果
            if (history.getStatus() != AiImageHistory.STATUS_PROCESSING) {
                if (history.getStatus() == AiImageHistory.STATUS_SUCCESS) {
                    // 查找该任务的所有相关图片
                    List<String> allImages = findAllImagesForTask(taskId);
                    AiImageResponse response = AiImageResponse.success(
                        history.getImageUrl(), 
                        taskId, 
                        history.getPrompt(), 
                        history.getSize(), 
                        history.getStyle()
                    );
                    response.setImageUrls(allImages);
                    return response;
                } else {
                    return AiImageResponse.failed(taskId, history.getPrompt(), "生成失败");
                }
            }
            
            // 调用API查询状态
            JsonNode apiResponse = doubaoPaintingClient.queryTaskStatus(taskId);
            String status = apiResponse.has("status") ? apiResponse.get("status").asText() : "processing";
            String imageUrl = apiResponse.has("image_url") ? apiResponse.get("image_url").asText() : null;
            
            if ("completed".equals(status) && imageUrl != null) {
                // 任务完成
                history.setImageUrl(imageUrl);
                history.setStatus(AiImageHistory.STATUS_SUCCESS);
                historyMapper.updateById(history);
                
                return AiImageResponse.success(imageUrl, taskId, history.getPrompt(), history.getSize(), history.getStyle());
                
            } else if ("failed".equals(status)) {
                // 任务失败
                history.setStatus(AiImageHistory.STATUS_FAILED);
                historyMapper.updateById(history);
                
                return AiImageResponse.failed(taskId, history.getPrompt(), "生成失败");
                
            } else {
                // 仍在处理中
                return AiImageResponse.processing(taskId, history.getPrompt(), history.getSize(), history.getStyle());
            }
            
        } catch (Exception e) {
            log.error("Failed to query task status: {}", e.getMessage(), e);
            return AiImageResponse.failed(taskId, "", "查询状态失败: " + e.getMessage());
        }
    }
    
    @Override
    public List<AiImageExample> getExamples() {
        LambdaQueryWrapper<AiImageExample> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AiImageExample::getStatus, AiImageExample.STATUS_ENABLED)
               .orderByAsc(AiImageExample::getSortOrder)
               .orderByDesc(AiImageExample::getCreateTime);
        
        return exampleMapper.selectList(wrapper);
    }
    
    @Override
    public List<AiImageExample> getExamplesWithUserWorks() {
        List<AiImageExample> result = new ArrayList<>();
        
        // 1. 获取系统示例（user_id为null的记录）
        LambdaQueryWrapper<AiImageExample> systemWrapper = new LambdaQueryWrapper<>();
        systemWrapper.eq(AiImageExample::getStatus, AiImageExample.STATUS_ENABLED)
                    .isNull(AiImageExample::getUserId)
                    .orderByAsc(AiImageExample::getSortOrder)
                    .orderByDesc(AiImageExample::getCreateTime);
        List<AiImageExample> systemExamples = exampleMapper.selectList(systemWrapper);
        result.addAll(systemExamples);
        
        // 2. 获取用户作品并转换为AiImageExample格式
        try {
            List<com.aipartner.entity.UserWork> userWorks = userWorkMapper.selectPublicWorks(0, 50);
            for (com.aipartner.entity.UserWork userWork : userWorks) {
                AiImageExample example = new AiImageExample();
                example.setId(userWork.getId());
                example.setTitle(userWork.getTitle());
                example.setImageUrl(userWork.getImageUrl());
                example.setPrompt(userWork.getPrompt());
                example.setStyle(userWork.getStyle());
                example.setSize(userWork.getSize());
                example.setUserId(userWork.getUserId());
                example.setLikeCount(userWork.getLikeCount());
                example.setViewCount(userWork.getViewCount());
                example.setStatus(userWork.getStatus());
                example.setCreateTime(userWork.getCreateTime());
                example.setUpdateTime(userWork.getUpdateTime());
                result.add(example);
            }
        } catch (Exception e) {
            // 如果用户作品表不存在或查询失败，只返回系统示例
            log.warn("Failed to fetch user works: {}", e.getMessage());
        }
        
        // 3. 按创建时间排序，最新的在前面
        result.sort((a, b) -> {
            if (a.getCreateTime() == null) return 1;
            if (b.getCreateTime() == null) return -1;
            return b.getCreateTime().compareTo(a.getCreateTime());
        });
        
        return result;
    }
    
    @Override
    public List<AiImageExample> getSystemExamples() {
        // 只获取系统示例（user_id为null的记录）
        LambdaQueryWrapper<AiImageExample> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AiImageExample::getStatus, AiImageExample.STATUS_ENABLED)
               .isNull(AiImageExample::getUserId)
               .orderByAsc(AiImageExample::getSortOrder)
               .orderByDesc(AiImageExample::getCreateTime);
        
        List<AiImageExample> systemExamples = exampleMapper.selectList(wrapper);
        
        log.info("获取到 {} 个系统示例图片", systemExamples.size());
        
        // 打印图片URL以便调试
        for (AiImageExample example : systemExamples) {
            log.info("示例图片: id={}, title={}, imageUrl={}", 
                    example.getId(), example.getTitle(), example.getImageUrl());
        }
        
        return systemExamples;
    }
    
    /**
     * 获取所有图片（系统示例 + 用户作品） - 统一接口
     */
    public List<AiImageExample> getAllImages() {
        LambdaQueryWrapper<AiImageExample> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AiImageExample::getStatus, AiImageExample.STATUS_ENABLED);
        
        List<AiImageExample> allImages = exampleMapper.selectList(wrapper);
        
        // 自定义排序：用户作品优先，按时间降序；然后是系统示例，按sort_order升序
        allImages.sort((a, b) -> {
            // 如果a是用户作品，b是系统示例，a优先
            if (a.getUserId() != null && b.getUserId() == null) {
                return -1;
            }
            // 如果a是系统示例，b是用户作品，b优先  
            if (a.getUserId() == null && b.getUserId() != null) {
                return 1;
            }
            // 如果都是用户作品，按创建时间降序（最新在前）
            if (a.getUserId() != null && b.getUserId() != null) {
                return b.getCreateTime().compareTo(a.getCreateTime());
            }
            // 如果都是系统示例，按sort_order升序，再按创建时间降序
            if (a.getUserId() == null && b.getUserId() == null) {
                int sortCompare = Integer.compare(a.getSortOrder(), b.getSortOrder());
                if (sortCompare != 0) {
                    return sortCompare;
                }
                return b.getCreateTime().compareTo(a.getCreateTime());
            }
            return 0;
        });
        log.info("获取到 {} 个图片（包含 {} 个系统示例和 {} 个用户作品）", 
                allImages.size(),
                allImages.stream().filter(img -> img.getUserId() == null).count(),
                allImages.stream().filter(img -> img.getUserId() != null).count());
        
        // 转换图片URL为完整路径并检查文件是否存在
        List<AiImageExample> validImages = new ArrayList<>();
        for (AiImageExample image : allImages) {
            if (image.getImageUrl() != null) {
                String originalUrl = image.getImageUrl();
                String publicUrl = buildPublicUrl(originalUrl);
                
                // 检查文件是否存在（仅针对用户作品）
                if (image.getUserId() != null) {
                    boolean fileExists = checkFileExists(originalUrl);
                    if (!fileExists) {
                        log.warn("用户作品文件不存在，跳过显示: userId={}, imageUrl={}", image.getUserId(), originalUrl);
                        continue; // 跳过不存在的文件
                    }
                }
                
                image.setImageUrl(publicUrl);
                log.debug("转换图片URL: {} -> {}", originalUrl, publicUrl);
            }
            validImages.add(image);
        }
        
        log.info("过滤后有效图片数量: {} (原始: {})", validImages.size(), allImages.size());
        return validImages;
    }
    
    @Override
    public Page<AiImageHistory> getUserHistory(Long userId, int page, int size) {
        Page<AiImageHistory> pageObj = new Page<>(page, size);
        
        LambdaQueryWrapper<AiImageHistory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AiImageHistory::getUserId, userId)
               .eq(AiImageHistory::getStatus, AiImageHistory.STATUS_SUCCESS) // 只返回成功的记录
               .isNotNull(AiImageHistory::getImageUrl) // 只返回有图片的记录
               .orderByDesc(AiImageHistory::getCreateTime);
        
        Page<AiImageHistory> result = historyMapper.selectPage(pageObj, wrapper);
        
        // 转换图片URL为完整路径，并查找所有相关图片
        result.getRecords().forEach(history -> {
            if (history.getImageUrl() != null) {
                String originalUrl = history.getImageUrl();
                String publicUrl = buildPublicUrl(originalUrl);
                log.info("转换历史记录图片URL: {} -> {}", originalUrl, publicUrl);
                history.setImageUrl(publicUrl);
                
                // 查找该任务的所有图片
                try {
                    List<String> allImages = findAllImagesForTask(history.getTaskId());
                    if (!allImages.isEmpty()) {
                        // 将所有图片URL转换为完整路径
                        List<String> publicUrls = allImages.stream()
                            .map(this::buildPublicUrl)
                            .collect(java.util.stream.Collectors.toList());
                        
                        // 设置到history对象中
                        history.setImageUrls(publicUrls);
                        log.info("任务 {} 找到 {} 张图片: {}", history.getTaskId(), publicUrls.size(), publicUrls);
                    }
                } catch (Exception e) {
                    log.warn("查找任务 {} 的所有图片时出错: {}", history.getTaskId(), e.getMessage());
                }
            }
        });
        
        return result;
    }
    
    @Override
    public AiImageHistory getHistoryById(Long id, Long userId) {
        LambdaQueryWrapper<AiImageHistory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AiImageHistory::getId, id)
               .eq(AiImageHistory::getUserId, userId);
        
        AiImageHistory history = historyMapper.selectOne(wrapper);
        
        // 转换图片URL为完整路径
        if (history != null && history.getImageUrl() != null) {
            history.setImageUrl(buildPublicUrl(history.getImageUrl()));
        }
        
        return history;
    }
    
    /**
     * 保存base64图片到文件系统
     */
    private String saveBase64Image(String base64Data, String taskId) throws IOException {
        try {
            // 创建上传目录
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }
            
            // 生成文件名
            String fileName = taskId + ".jpg";
            File file = new File(uploadDir, fileName);
            
            // 解码base64并保存文件
            String pureBase64 = base64Data;
            int commaIdx = base64Data.indexOf(",");
            if (base64Data.startsWith("data:" ) && commaIdx > 0) {
                pureBase64 = base64Data.substring(commaIdx + 1);
            }
            byte[] imageBytes = Base64.getDecoder().decode(pureBase64);
            try (FileOutputStream fos = new FileOutputStream(file)) {
                fos.write(imageBytes);
            }
            
            // 返回访问URL（补全绝对前缀）
            String relative = urlPrefix + fileName;
            String publicUrl = buildPublicUrl(relative);
            log.info("生成图片已保存: path={}, publicUrl={}", file.getAbsolutePath(), publicUrl);
            return publicUrl;
            
        } catch (Exception e) {
            log.error("Failed to save base64 image: {}", e.getMessage(), e);
            throw new IOException("保存图片失败", e);
        }
    }

    /**
     * 从URL下载图片并保存到文件系统
     */
    private String downloadImageFromUrl(String imageUrl, String taskId) throws IOException {
        try {
            // 创建上传目录
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }

            String fileName = taskId + ".jpg";
            File file = new File(uploadDir, fileName);

            java.net.URL url = new java.net.URL(imageUrl);
            java.net.HttpURLConnection conn = (java.net.HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(15000);
            conn.setReadTimeout(60000);
            conn.setInstanceFollowRedirects(true);
            conn.connect();
            int status = conn.getResponseCode();
            String contentType = conn.getContentType();
            if (status != 200 || contentType == null || !contentType.startsWith("image/")) {
                String bodySnippet = null;
                try (java.io.InputStream err = (status >= 400 ? conn.getErrorStream() : conn.getInputStream())) {
                    if (err != null) {
                        byte[] buf = new byte[2048];
                        int n = err.read(buf);
                        if (n > 0) {
                            bodySnippet = new String(buf, 0, n, java.nio.charset.StandardCharsets.UTF_8);
                        }
                    }
                } catch (Exception ignore) {}
                log.error("远程URL返回的内容不是图片: status={}, contentType={}, bodySnippet={}", status, contentType, bodySnippet);
                throw new IOException("上游未返回图片数据");
            }
            try (java.io.InputStream in = conn.getInputStream();
                 java.io.FileOutputStream out = new java.io.FileOutputStream(file)) {
                byte[] buffer = new byte[8192];
                int bytesRead;
                while ((bytesRead = in.read(buffer)) != -1) {
                    out.write(buffer, 0, bytesRead);
                }
            } finally {
                conn.disconnect();
            }
            String relative = urlPrefix + fileName;
            String publicUrl = buildPublicUrl(relative);
            log.info("已下载远程图片: sourceUrl={}, path={}, publicUrl={}", imageUrl, file.getAbsolutePath(), publicUrl);
            return publicUrl;
        } catch (Exception e) {
            log.error("Failed to download image from URL {}: {}", imageUrl, e.getMessage(), e);
            throw new IOException("下载图片失败", e);
        }
    }

    private String buildPublicUrl(String path) {
        if (path == null) return null;
        if (path.startsWith("http://") || path.startsWith("https://")) {
            return path;
        }
        
        String base = externalBaseUrl;
        if (base.endsWith("/")) {
            base = base.substring(0, base.length() - 1);
        }
        return base + path;
    }
    
    /**
     * 检查文件是否存在
     */
    private boolean checkFileExists(String imagePath) {
        try {
            if (imagePath == null) return false;
            
            // 处理不同的路径格式
            String filePath;
            if (imagePath.startsWith("/uploads/generated-images/")) {
                filePath = imagePath.substring("/uploads/generated-images/".length());
                File file = new File(uploadPath, filePath);
                boolean exists = file.exists();
                log.debug("检查生成图片文件: {} -> 存在: {}", file.getAbsolutePath(), exists);
                return exists;
            } else if (imagePath.startsWith("/uploads/illustrate-images/")) {
                filePath = imagePath.substring("/uploads/".length());
                File file = new File("uploads", filePath);
                boolean exists = file.exists();
                log.debug("检查示例图片文件: {} -> 存在: {}", file.getAbsolutePath(), exists);
                return exists;
            }
            
            // 默认认为文件存在（避免误删系统示例）
            return true;
        } catch (Exception e) {
            log.error("检查文件存在性时出错: {}", e.getMessage());
            return true; // 出错时默认认为存在，避免误删
        }
    }
    
    /**
     * 查找任务相关的所有图片
     */
    private List<String> findAllImagesForTask(String taskId) {
        List<String> images = new ArrayList<>();
        
        // 生成的图片文件路径
        File uploadDir = new File(uploadPath);
        if (uploadDir.exists() && uploadDir.isDirectory()) {
            File[] files = uploadDir.listFiles((dir, name) -> 
                name.startsWith(taskId) && (name.endsWith(".jpg") || name.endsWith(".png")));
            
            if (files != null) {
                // 按文件名排序，确保顺序一致（taskId_1, taskId_2, taskId_3）
                java.util.Arrays.sort(files, (f1, f2) -> f1.getName().compareTo(f2.getName()));
                
                for (File file : files) {
                    String publicUrl = buildPublicUrl(urlPrefix + file.getName());
                    images.add(publicUrl);
                }
            }
        }
        
        log.info("找到任务 {} 的图片文件: {}", taskId, images);
        return images;
    }
    
    /**
     * 复制图片文件
     */
    private String copyImage(String sourceUrl, String newTaskId) throws IOException {
        try {
            // 从源URL中提取文件名
            String sourceFileName = sourceUrl.substring(sourceUrl.lastIndexOf("/") + 1);
            File sourceFile = new File(uploadPath, sourceFileName);
            
            if (!sourceFile.exists()) {
                throw new IOException("源图片文件不存在: " + sourceFile.getAbsolutePath());
            }
            
            // 创建新文件
            String newFileName = newTaskId + ".jpg";
            File newFile = new File(uploadPath, newFileName);
            
            // 复制文件
            java.nio.file.Files.copy(sourceFile.toPath(), newFile.toPath(), 
                java.nio.file.StandardCopyOption.REPLACE_EXISTING);
            
            String newUrl = buildPublicUrl(urlPrefix + newFileName);
            log.info("图片复制成功: {} -> {}", sourceFile.getName(), newFile.getName());
            return newUrl;
        } catch (Exception e) {
            log.error("复制图片失败: {}", e.getMessage(), e);
            throw new IOException("复制图片失败", e);
        }
    }
    
    @Override
    public boolean deleteHistory(Long id, Long userId) {
        try {
            log.info("开始删除历史记录 - ID: {}, 用户ID: {}", id, userId);
            
            // 先查询记录是否存在且属于当前用户
            LambdaQueryWrapper<AiImageHistory> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(AiImageHistory::getId, id)
                       .eq(AiImageHistory::getUserId, userId);
            
            AiImageHistory history = historyMapper.selectOne(queryWrapper);
            log.info("查询结果: {}", history);
            
            if (history == null) {
                // 再查询一下是否记录存在但用户不匹配
                AiImageHistory anyHistory = historyMapper.selectById(id);
                if (anyHistory != null) {
                    log.warn("记录 {} 存在但属于用户 {}, 当前用户 {} 无权限删除", id, anyHistory.getUserId(), userId);
                } else {
                    log.warn("记录 {} 不存在", id);
                    
                    // 查询当前用户的所有记录，用于调试
                    LambdaQueryWrapper<AiImageHistory> userQuery = new LambdaQueryWrapper<>();
                    userQuery.eq(AiImageHistory::getUserId, userId);
                    List<AiImageHistory> userRecords = historyMapper.selectList(userQuery);
                    log.info("当前用户 {} 的所有历史记录: {}", userId, userRecords.stream()
                        .map(AiImageHistory::getId)
                        .collect(java.util.stream.Collectors.toList()));
                }
                return false;
            }
            
            // 删除数据库记录
            int deleted = historyMapper.deleteById(id);
            if (deleted > 0) {
                log.info("成功删除用户 {} 的历史记录: {}", userId, id);
                
                // 可选：删除相关的图片文件
                // deleteImageFiles(history);
                
                return true;
            } else {
                log.error("删除历史记录失败，数据库操作返回0: {}", id);
                return false;
            }
        } catch (Exception e) {
            log.error("删除历史记录异常: {}", e.getMessage(), e);
            return false;
        }
    }
    
    /**
     * 删除历史记录相关的图片文件（可选功能）
     */
    private void deleteImageFiles(AiImageHistory history) {
        try {
            if (history.getImageUrls() != null && !history.getImageUrls().isEmpty()) {
                for (String imageUrl : history.getImageUrls()) {
                    // 从URL中提取文件名
                    String fileName = imageUrl.substring(imageUrl.lastIndexOf("/") + 1);
                    File imageFile = new File(uploadPath, fileName);
                    if (imageFile.exists() && imageFile.delete()) {
                        log.info("删除图片文件: {}", fileName);
                    }
                }
            }
        } catch (Exception e) {
            log.error("删除图片文件失败: {}", e.getMessage(), e);
        }
    }
    
    @Override
    public boolean deleteHistoryByTaskId(String taskId, Long userId) {
        try {
            log.info("通过taskId删除历史记录 - taskId: {}, 用户ID: {}", taskId, userId);
            
            // 先查询记录是否存在且属于当前用户
            LambdaQueryWrapper<AiImageHistory> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(AiImageHistory::getTaskId, taskId)
                       .eq(AiImageHistory::getUserId, userId);
            
            AiImageHistory history = historyMapper.selectOne(queryWrapper);
            log.info("通过taskId查询结果: {}", history);
            
            if (history == null) {
                log.warn("用户 {} 尝试删除不存在或无权限的历史记录，taskId: {}", userId, taskId);
                return false;
            }
            
            // 删除数据库记录
            int deleted = historyMapper.deleteById(history.getId());
            if (deleted > 0) {
                log.info("成功删除用户 {} 的历史记录: {} (taskId: {})", userId, history.getId(), taskId);
                return true;
            } else {
                log.error("删除历史记录失败，数据库操作返回0: {}", history.getId());
                return false;
            }
        } catch (Exception e) {
            log.error("通过taskId删除历史记录异常: {}", e.getMessage(), e);
            return false;
        }
    }

    @Override
    public String uploadReferenceImage(MultipartFile file, Long userId) {
        try {
            // 确保目录存在
            File uploadDir = new File(referenceImagesPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }
            
            // 生成文件名
            String originalFilename = file.getOriginalFilename();
            String extension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            
            String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
            String filename = "ref_" + userId + "_" + timestamp + "_" + UUID.randomUUID().toString().substring(0, 8) + extension;
            
            // 保存文件
            Path filePath = Paths.get(referenceImagesPath, filename);
            Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);
            
            // 生成公开访问URL
            String imageUrl = buildPublicUrl(referenceImagesUrlPrefix + filename);
            
            log.info("参考图上传成功: userId={}, filename={}, url={}", userId, filename, imageUrl);
            
            return imageUrl;
            
        } catch (Exception e) {
            log.error("上传参考图失败: userId={}, error={}", userId, e.getMessage(), e);
            throw new RuntimeException("上传参考图失败: " + e.getMessage());
        }
    }
    
    // ==================== 管理端统计方法实现 ====================
    
    @Override
    public Map<String, Object> getAdminAiImageStats() {
        Map<String, Object> stats = new HashMap<>();
        
        try {
            log.info("开始查询AI生图统计数据");
            
            // 查询总生成次数
            QueryWrapper<AiImageHistory> totalWrapper = new QueryWrapper<>();
            long totalGenerations = historyMapper.selectCount(totalWrapper);
            log.info("总生成次数查询结果: {}", totalGenerations);
            
            // 查询成功生成次数
            QueryWrapper<AiImageHistory> successWrapper = new QueryWrapper<>();
            successWrapper.eq("status", AiImageHistory.STATUS_SUCCESS);
            long successGenerations = historyMapper.selectCount(successWrapper);
            log.info("成功生成次数查询结果: {}", successGenerations);
            
            // 查询今日生成次数
            LocalDateTime todayStart = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0);
            QueryWrapper<AiImageHistory> todayWrapper = new QueryWrapper<>();
            todayWrapper.ge("create_time", todayStart);
            long todayGenerations = historyMapper.selectCount(todayWrapper);
            log.info("今日生成次数查询结果: {} (todayStart: {})", todayGenerations, todayStart);
            
            // 查询本月生成次数
            LocalDateTime monthStart = LocalDateTime.now().withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0);
            QueryWrapper<AiImageHistory> monthWrapper = new QueryWrapper<>();
            monthWrapper.ge("create_time", monthStart);
            long monthGenerations = historyMapper.selectCount(monthWrapper);
            log.info("本月生成次数查询结果: {} (monthStart: {})", monthGenerations, monthStart);
            
            // 计算成功率
            double successRate = totalGenerations > 0 ? (double) successGenerations / totalGenerations * 100 : 0;
            
            // 查询活跃用户数（本月有生图记录的用户）
            QueryWrapper<AiImageHistory> activeUsersWrapper = new QueryWrapper<>();
            activeUsersWrapper.ge("create_time", monthStart)
                             .select("DISTINCT user_id");
            List<AiImageHistory> activeUsers = historyMapper.selectList(activeUsersWrapper);
            long activeUserCount = activeUsers.size();
            log.info("活跃用户数查询结果: {}", activeUserCount);
            
            stats.put("totalGenerations", totalGenerations);
            stats.put("successGenerations", successGenerations);
            stats.put("todayGenerations", todayGenerations);
            stats.put("monthGenerations", monthGenerations);
            stats.put("successRate", Math.round(successRate * 100.0) / 100.0);
            stats.put("activeUserCount", activeUserCount);
            
            log.info("AI生图统计数据汇总: {}", stats);
            
        } catch (Exception e) {
            log.error("获取AI生图统计数据失败", e);
            // 返回默认值
            stats.put("totalGenerations", 0);
            stats.put("successGenerations", 0);
            stats.put("todayGenerations", 0);
            stats.put("monthGenerations", 0);
            stats.put("successRate", 0.0);
            stats.put("activeUserCount", 0);
        }
        
        return stats;
    }
    
    @Override
    public Page<AiImageHistory> getAdminAiImageHistory(Page<AiImageHistory> page, String keyword, String status) {
        log.info("=== Service开始查询AI生图历史记录 ===");
        log.info("输入的分页对象: current={}, size={}", page.getCurrent(), page.getSize());
        log.info("输入参数: keyword={}, status={}", keyword, status);
        
        QueryWrapper<AiImageHistory> wrapper = new QueryWrapper<>();
        
        // 关键词搜索
        if (StringUtils.hasText(keyword)) {
            wrapper.and(w -> w.like("prompt", keyword)
                           .or().eq("user_id", keyword)
                           .or().like("task_id", keyword));
            log.info("添加关键词搜索条件: {}", keyword);
        }
        
        // 状态筛选
        if (StringUtils.hasText(status)) {
            switch (status) {
                case "processing":
                    wrapper.eq("status", AiImageHistory.STATUS_PROCESSING);
                    log.info("添加状态筛选: processing ({})", AiImageHistory.STATUS_PROCESSING);
                    break;
                case "completed":
                    wrapper.eq("status", AiImageHistory.STATUS_SUCCESS);
                    log.info("添加状态筛选: completed ({})", AiImageHistory.STATUS_SUCCESS);
                    break;
                case "failed":
                    wrapper.eq("status", AiImageHistory.STATUS_FAILED);
                    log.info("添加状态筛选: failed ({})", AiImageHistory.STATUS_FAILED);
                    break;
            }
        }
        
        // 按创建时间排序
        wrapper.orderByDesc("create_time");
        
        try {
            log.info("调用Mapper前的分页对象: current={}, size={}", page.getCurrent(), page.getSize());
            Page<AiImageHistory> result = historyMapper.selectPage(page, wrapper);
            log.info("Mapper返回的分页对象: current={}, size={}, total={}, pages={}, records={}", 
                    result.getCurrent(), result.getSize(), result.getTotal(), result.getPages(), result.getRecords().size());
            
            // 验证分页参数是否被修改
            if (result.getCurrent() != page.getCurrent()) {
                log.warn("警告：分页current参数被修改 - 输入:{}, 输出:{}", page.getCurrent(), result.getCurrent());
            }
            if (result.getSize() != page.getSize()) {
                log.warn("警告：分页size参数被修改 - 输入:{}, 输出:{}", page.getSize(), result.getSize());
            }
            
            if (result.getRecords().size() > 0) {
                log.info("第一条记录: {}", result.getRecords().get(0));
            }
            log.info("=== Service查询AI生图历史记录完成 ===");
            return result;
        } catch (Exception e) {
            log.error("查询AI生图历史记录失败", e);
            return new Page<>();
        }
    }
    
    @Override
    public boolean adminDeleteAiImageRecord(Long recordId) {
        log.info("管理员删除AI生图记录: recordId={}", recordId);
        
        try {
            // 先获取记录信息，用于日志
            AiImageHistory record = historyMapper.selectById(recordId);
            if (record == null) {
                log.warn("要删除的AI生图记录不存在: recordId={}", recordId);
                return false;
            }
            
            log.info("准备删除AI生图记录: recordId={}, userId={}, taskId={}, prompt={}", 
                    recordId, record.getUserId(), record.getTaskId(), record.getPrompt());
            
            // 执行删除
            int result = historyMapper.deleteById(recordId);
            
            if (result > 0) {
                log.info("成功删除AI生图记录: recordId={}", recordId);
                return true;
            } else {
                log.warn("删除AI生图记录失败，未找到记录: recordId={}", recordId);
                return false;
            }
        } catch (Exception e) {
            log.error("删除AI生图记录异常: recordId={}", recordId, e);
            return false;
        }
    }
    
    // ==================== 用户作品管理方法 ====================
    
    @Override
    public Page<com.aipartner.entity.UserWork> getAdminUserWorkList(Page<com.aipartner.entity.UserWork> page, String keyword, String status, String isPublic) {
        log.info("获取管理端用户作品列表: page={}, size={}, keyword={}, status={}, isPublic={}", 
                page.getCurrent(), page.getSize(), keyword, status, isPublic);
        
        try {
            // 查询 ai_image_examples 表中有 userId 的记录（用户作品）
            QueryWrapper<AiImageExample> queryWrapper = new QueryWrapper<>();
            queryWrapper.isNotNull("user_id");  // 只查询用户上传的作品
            
            // 关键词搜索：标题、提示词
            if (StringUtils.hasText(keyword)) {
                queryWrapper.and(wrapper -> wrapper.like("title", keyword).or().like("prompt", keyword));
            }
            
            // 状态筛选
            if (StringUtils.hasText(status)) {
                try {
                    Integer statusInt = Integer.parseInt(status);
                    queryWrapper.eq("status", statusInt);
                } catch (NumberFormatException e) {
                    log.warn("无效的状态参数: {}", status);
                }
            }
            
            // 审核状态筛选 (用 isPublic 参数来表示审核状态)
            if (StringUtils.hasText(isPublic)) {
                try {
                    Integer reviewStatusInt = Integer.parseInt(isPublic);
                    if (reviewStatusInt == 1) {
                        queryWrapper.eq("review_status", AiImageExample.REVIEW_STATUS_APPROVED);
                    } else if (reviewStatusInt == 0) {
                        queryWrapper.in("review_status", 
                            AiImageExample.REVIEW_STATUS_PENDING, AiImageExample.REVIEW_STATUS_REJECTED);
                    }
                } catch (NumberFormatException e) {
                    log.warn("无效的审核状态参数: {}", isPublic);
                }
            }
            
            // 按创建时间倒序
            queryWrapper.orderByDesc("create_time");
            
            Page<AiImageExample> examplePage = new Page<>(page.getCurrent(), page.getSize());
            Page<AiImageExample> result = exampleMapper.selectPage(examplePage, queryWrapper);
            
            // 转换为 UserWork 格式以兼容前端
            Page<com.aipartner.entity.UserWork> userWorkPage = new Page<>();
            userWorkPage.setCurrent(result.getCurrent());
            userWorkPage.setSize(result.getSize());
            userWorkPage.setTotal(result.getTotal());
            userWorkPage.setPages(result.getPages());
            
            java.util.List<com.aipartner.entity.UserWork> userWorks = new java.util.ArrayList<>();
            for (AiImageExample example : result.getRecords()) {
                com.aipartner.entity.UserWork userWork = new com.aipartner.entity.UserWork();
                userWork.setId(example.getId());
                userWork.setUserId(example.getUserId());
                userWork.setTitle(example.getTitle());
                
                // 调试日志：查看原始图片URL
                log.info("处理用户作品图片URL: workId={}, 原始URL=[{}]", example.getId(), example.getImageUrl());
                
                // 确保图片URL包含完整域名
                String fullImageUrl = buildFullImageUrl(example.getImageUrl());
                userWork.setImageUrl(fullImageUrl);
                
                log.info("处理用户作品图片URL: workId={}, 完整URL=[{}]", example.getId(), fullImageUrl);
                
                userWork.setPrompt(example.getPrompt());
                userWork.setStyle(example.getStyle());
                userWork.setSize(example.getSize());
                
                // 实时计算点赞数量
                QueryWrapper<UserWorkLike> likeWrapper = new QueryWrapper<>();
                likeWrapper.eq("work_id", example.getId());
                long likeCount = userWorkLikeMapper.selectCount(likeWrapper);
                userWork.setLikeCount((int) likeCount);
                
                userWork.setViewCount(example.getViewCount() != null ? example.getViewCount() : 0);
                
                // 计算评论数量
                QueryWrapper<AiImageExampleChat> commentWrapper = new QueryWrapper<>();
                commentWrapper.eq("example_id", example.getId());
                long commentCount = exampleChatMapper.selectCount(commentWrapper);
                userWork.setCommentCount((int) commentCount);
                
                userWork.setStatus(example.getStatus());
                userWork.setIsPublic(example.getReviewStatus()); // 用审核状态表示公开状态
                userWork.setCreateTime(example.getCreateTime());
                userWork.setUpdateTime(example.getUpdateTime());
                userWorks.add(userWork);
            }
            userWorkPage.setRecords(userWorks);
            
            log.info("查询到用户作品数量: total={}, records={}", userWorkPage.getTotal(), userWorks.size());
            return userWorkPage;
            
        } catch (Exception e) {
            log.error("获取管理端用户作品列表失败", e);
            throw e;
        }
    }
    
    /**
     * 构建完整的图片URL
     */
    private String buildFullImageUrl(String imageUrl) {
        if (imageUrl == null || imageUrl.isEmpty()) {
            return null;
        }
        
        // 检查无效的URL格式，直接返回null让前端显示占位符
        if (imageUrl.equals("INVALID_URL") ||
            imageUrl.startsWith("wxfile://") || 
            imageUrl.startsWith("file://") ||
            imageUrl.contains("tmp/") ||
            imageUrl.contains("//tmp")) {
            log.warn("检测到无效图片URL格式，设置为null: [{}]", imageUrl);
            return null;
        }
        
        // 如果已经是有效的完整URL，直接返回
        if (imageUrl.startsWith("http://") || imageUrl.startsWith("https://")) {
            // 但要排除明显错误的URL（如包含tmp路径的）
            if (imageUrl.contains("/tmp/") || imageUrl.contains("//tmp")) {
                log.warn("检测到包含tmp路径的无效完整URL，设置为null: [{}]", imageUrl);
                return null;
            }
            return imageUrl;
        }
        
        // 只处理正确的相对路径格式（以/uploads/开头）
        if (!imageUrl.startsWith("/uploads/")) {
            log.warn("检测到非标准相对路径格式，设置为null: [{}]", imageUrl);
            return null;
        }
        
        // 规范化baseUrl - 确保没有尾部斜杠
        String baseUrl = externalBaseUrl;
        if (baseUrl.endsWith("/")) {
            baseUrl = baseUrl.substring(0, baseUrl.length() - 1);
        }
        
        // 构建完整URL
        String fullUrl = baseUrl + imageUrl;
        
        // 替换任何双斜杠（除了协议后的://）
        fullUrl = fullUrl.replaceAll("(?<!:)//+", "/");
        
        log.info("构建图片URL: 原始=[{}], 完整=[{}]", imageUrl, fullUrl);
        return fullUrl;
    }
    
    @Override
    public boolean adminDeleteUserWork(Long workId) {
        log.info("管理员删除用户作品: workId={}", workId);
        
        try {
            // 从 ai_image_examples 表中获取作品信息
            AiImageExample example = exampleMapper.selectById(workId);
            if (example == null || example.getUserId() == null) {
                log.warn("要删除的用户作品不存在: workId={}", workId);
                return false;
            }
            
            log.info("准备删除用户作品: workId={}, userId={}, title={}, prompt={}", 
                    workId, example.getUserId(), example.getTitle(), example.getPrompt());
            
            // 执行删除
            int result = exampleMapper.deleteById(workId);
            
            if (result > 0) {
                log.info("成功删除用户作品: workId={}", workId);
                return true;
            } else {
                log.warn("删除用户作品失败，未找到作品: workId={}", workId);
                return false;
            }
        } catch (Exception e) {
            log.error("删除用户作品异常: workId={}", workId, e);
            return false;
        }
    }
    
    @Override
    public Map<String, Object> getAdminUserWorkStats() {
        log.info("获取管理端用户作品统计数据");
        
        try {
            Map<String, Object> stats = new HashMap<>();
            
            // 总作品数（只统计用户上传的作品）
            QueryWrapper<AiImageExample> totalWrapper = new QueryWrapper<>();
            totalWrapper.isNotNull("user_id");
            Long totalWorks = exampleMapper.selectCount(totalWrapper);
            stats.put("totalWorks", totalWorks);
            
            // 已审核通过作品数
            QueryWrapper<AiImageExample> approvedWrapper = new QueryWrapper<>();
            approvedWrapper.isNotNull("user_id").eq("review_status", AiImageExample.REVIEW_STATUS_APPROVED);
            Long publicWorks = exampleMapper.selectCount(approvedWrapper);
            stats.put("publicWorks", publicWorks);
            
            // 显示状态作品数
            QueryWrapper<AiImageExample> activeWrapper = new QueryWrapper<>();
            activeWrapper.isNotNull("user_id").eq("status", AiImageExample.STATUS_ENABLED);
            Long activeWorks = exampleMapper.selectCount(activeWrapper);
            stats.put("activeWorks", activeWorks);
            
            // 今日新增作品数
            QueryWrapper<AiImageExample> todayWrapper = new QueryWrapper<>();
            todayWrapper.isNotNull("user_id").apply("DATE(create_time) = CURDATE()");
            Long todayWorks = exampleMapper.selectCount(todayWrapper);
            stats.put("todayWorks", todayWorks);
            
            // 本月新增作品数
            QueryWrapper<AiImageExample> monthWrapper = new QueryWrapper<>();
            monthWrapper.isNotNull("user_id").apply("YEAR(create_time) = YEAR(CURDATE()) AND MONTH(create_time) = MONTH(CURDATE())");
            Long monthWorks = exampleMapper.selectCount(monthWrapper);
            stats.put("monthWorks", monthWorks);
            
            // 总点赞数
            List<Map<String, Object>> likeResult = exampleMapper.selectMaps(
                new QueryWrapper<AiImageExample>()
                    .select("IFNULL(SUM(like_count), 0) as totalLikes")
                    .isNotNull("user_id")
            );
            Long totalLikes = 0L;
            if (!likeResult.isEmpty()) {
                Object likesObj = likeResult.get(0).get("totalLikes");
                if (likesObj != null) {
                    totalLikes = ((Number) likesObj).longValue();
                }
            }
            stats.put("totalLikes", totalLikes);
            
            // 总浏览数
            List<Map<String, Object>> viewResult = exampleMapper.selectMaps(
                new QueryWrapper<AiImageExample>()
                    .select("IFNULL(SUM(view_count), 0) as totalViews")
                    .isNotNull("user_id")
            );
            Long totalViews = 0L;
            if (!viewResult.isEmpty()) {
                Object viewsObj = viewResult.get(0).get("totalViews");
                if (viewsObj != null) {
                    totalViews = ((Number) viewsObj).longValue();
                }
            }
            stats.put("totalViews", totalViews);
            
            log.info("用户作品统计数据: {}", stats);
            return stats;
            
        } catch (Exception e) {
            log.error("获取用户作品统计数据失败", e);
            throw e;
        }
    }
    
    @Override
    public boolean adminUpdateUserWorkStatus(Long workId, Integer status) {
        log.info("管理员更新用户作品状态: workId={}, status={}", workId, status);
        
        try {
            // 从 ai_image_examples 表中检查作品是否存在
            AiImageExample example = exampleMapper.selectById(workId);
            if (example == null || example.getUserId() == null) {
                log.warn("要更新状态的用户作品不存在: workId={}", workId);
                return false;
            }
            
            // 更新状态
            AiImageExample updateExample = new AiImageExample();
            updateExample.setId(workId);
            updateExample.setStatus(status);
            updateExample.setUpdateTime(LocalDateTime.now());
            
            int result = exampleMapper.updateById(updateExample);
            
            if (result > 0) {
                String statusText = status == 1 ? "显示" : "隐藏";
                log.info("成功更新用户作品状态: workId={}, status={} ({})", workId, status, statusText);
                return true;
            } else {
                log.warn("更新用户作品状态失败: workId={}, status={}", workId, status);
                return false;
            }
        } catch (Exception e) {
            log.error("更新用户作品状态异常: workId={}, status={}", workId, status, e);
            return false;
        }
    }
}
